/*
 * Created on 2005-6-21
 *
 */
package com.yl.cap.analyst.user.actions;

import jaoso.framework.domain.Account;
import jaoso.framework.exception.GroupExistException;
import jaoso.framework.service.SecurityService;
import jaoso.framework.util.MD5;
import jaoso.framework.util.MyUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Category;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.yl.cap.analyst.exceptions.GroupConflictException;
import com.yl.cap.analyst.exceptions.UserExistException;
import com.yl.cap.analyst.user.domain.Group;
import com.yl.cap.analyst.user.domain.User;
import com.yl.cap.analyst.user.service.UserService;

/**
 * @author ZhangQi
 *  
 */
public class ReportUserAction extends DispatchAction
{
    Category log = Logger.getLogger("reporte");
    
    private UserService getService()
    {
        ApplicationContext ctx = WebApplicationContextUtils
                .getWebApplicationContext(this.getServlet().getServletContext());
        return (UserService) ctx.getBean("userService");
    }

    private SecurityService getSecurityService()
    {
        ApplicationContext ctx = WebApplicationContextUtils
                .getWebApplicationContext(this.getServlet().getServletContext());
        return (SecurityService) ctx.getBean("securityService");
    }

    public final ActionForward createGroup(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        String groupName = request.getParameter("groupName");
        String popedomField = request.getParameter("popedomField");
        Group group = new Group();
        group.setName(groupName);
        group.setPopedomField(popedomField);

        UserService service = getService();

        try
        {
            service.createGroup(group);
        }
        catch (GroupExistException e)
        {
            log.error("createGroup error: " + e);
            errors.add("createGroup", new ActionError("errors.GroupExist"));
        }
        catch (Exception e)
        {
            log.error("createGroup error: " + e);
            errors.add("createGroup", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);
            return mapping.findForward("faile");
        }

        return mapping.findForward("success");
    }

    public final ActionForward listGroups(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        List groups = null;

        UserService service = getService();

        try
        {
            groups = service.getAllGroup();
        }
        catch (Exception e)
        {
            log.error("listGroups error: " + e);
            errors.add("listGroups", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);

            return mapping.findForward("faile");
        }

        request.setAttribute("groups", groups);
        return mapping.findForward("grouplist");
    }

    public final ActionForward listUser(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        Account[] accounts = null;

        SecurityService service = getSecurityService();

        try
        {
            accounts = service.findAllAccount();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            log.error("listUsers error: " + e);
            errors.add("listUsers", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);

            return mapping.findForward("faile");
        }

        request.setAttribute("accounts", accounts);
        return mapping.findForward("userlist");
    }

    public final ActionForward showCreateUser(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        List groups = null;

        UserService service = getService();

        try
        {
            groups = service.getAllGroup();
        }
        catch (Exception e)
        {
            log.error("showCreateUser error: " + e);
            errors.add("showCreateUser", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);

            return mapping.findForward("faile");
        }

        request.setAttribute("groups", groups);
        return mapping.findForward("createuser");
    }

    public final ActionForward updGroup(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String popedom = request.getParameter("popedomField");

        UserService service = getService();

        try
        {
            Group group = new Group();
            group.setId(id);
            group.setName(name);
            group.setPopedomField(popedom);
            service.updGroup(group);
        }
        catch (GroupExistException e)
        {
            log.error("updGroup error: " + e);
            errors.add("updGroup", new ActionError("errors.GroupExist"));
        }
        catch (Exception e)
        {
            log.error("updGroup error: " + e);
            errors.add("updGroup", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);
            return mapping.findForward("faile");
        }

        return mapping.findForward("success");
    }

    public final ActionForward removeUser(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        String ids[] = request.getParameterValues("id");

        UserService service = getService();

        try
        {
            service.delUser(ids);
        }
        catch (Exception e)
        {
            log.error("removeUser error: ", e);
            errors.add("removeUser", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);

            return mapping.findForward("faile");
        }

        return (mapping.findForward("success"));
    }

    public final ActionForward removeGroup(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        String ids[] = request.getParameterValues("group");
        /*for (int i = 0; i < ids.length; i++)
        {
            ids[i] = ids[i].substring(0, ids[i].indexOf(":"));
        }*/

        UserService service = getService();

        try
        {
            service.delGroups(ids);
        }
        catch (UserExistException e)
        {
            log.error("removeGroup error: ", e);
            errors.add("removeGroup", new ActionError("errors.HaveUserError"));
        }
        catch (Exception e)
        {
            log.error("removeGroup error: ", e);
            errors.add("removeGroup", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);

            return mapping.findForward("faile");
        }

        return (mapping.findForward("success"));
    }

    public final ActionForward createUser(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        String name = request.getParameter("loginName");
        String realName = request.getParameter("realName");
        String email = request.getParameter("email");
        String groupIds = request.getParameter("groupId");
        StringTokenizer st = new StringTokenizer(groupIds,",");
        Set groups = new HashSet();
        while (st.hasMoreTokens())
        {
            groups.add(st.nextToken());
        }

        User user = new User();
        user.setEmail(email);
        user.setRealName(realName);
        //Group group = new Group();
        //group.setId(groupId);
        user.setGroups(groups);
        Account account = new Account();
        account.setName(name);
        account.setUser(user);
        account.setPassword(MyUtils.toMD5("123456"));
        user.setAccount(account);

        UserService service = getService();

        try
        {
            service.createUser(user);
        }
        catch (UserExistException e)
        {
            log.error("createUser error: " + e);
            errors.add("createUser", new ActionError("errors.UserExist"));
        }
        catch (GroupConflictException e)
        {
            log.error("createUser error: " + e);
            errors.add("createUser", new ActionError("errors.GroupConflict"));
        }
        catch (Exception e)
        {
            log.error("createUser error: " + e);
            errors.add("createUser", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);
            return mapping.findForward("faile");
        }

        return mapping.findForward("success");
    }

    public final ActionForward viewUser(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        String id = request.getParameter("id");
        List allGroups = null;
        List groups = new ArrayList();
        
        Account a = null;

        UserService service = getService();

        try
        {
            a = service.getUserById(id);
            allGroups = service.getAllGroup();
            boolean isContain = false;
            for (int i = 0; i < allGroups.size(); i++)
            {
                for (Iterator j = a.getUser().getGroups().iterator(); j.hasNext();)
                {
                    if (((Group)j.next()).getId().equals(((Group)allGroups.get(i)).getId()))
                    {
                        isContain = true;
                        break;
                    }
                }
                if (!isContain)
                {
                    groups.add(allGroups.get(i));
                }
                isContain = false;
            }
        }
        catch (Exception e)
        {
            log.error("viewUser error: ", e);
            errors.add("viewUser", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);

            return mapping.findForward("faile");
        }

        request.setAttribute("account", a);
        request.setAttribute("groups", groups);

        return (mapping.findForward("edituser"));
    }

    public final ActionForward updUser(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        Account account = new Account();
        account.setId(request.getParameter("id"));
        account.setName(request.getParameter("loginName"));
        String pass = request.getParameter("repassword");
        String email = request.getParameter("email");
        String groupIds = request.getParameter("groupId");
        StringTokenizer st = new StringTokenizer(groupIds,",");
        Set groups = new HashSet();
        while (st.hasMoreTokens())
        {
            Group tmpGroup = new Group();
            tmpGroup.setId(st.nextToken());
            groups.add(tmpGroup);
        }
        
        if (pass != null && !pass.equals(""))
        {
            account.setPassword(pass);
        }
        User user = new User();
        user.setEmail(email);
        user.setId(request.getParameter("userId"));
        user.setRealName(request.getParameter("realName"));
        //Group group = new Group();
        //group.setId(request.getParameter("groupId"));
        user.setGroups(groups);
        user.setAccount(account);
        account.setUser(user);

        try
        {
            SecurityService service = getSecurityService();
            service.updateAccount(account);
        }
        catch (GroupConflictException e)
        {
            log.error("updUser error: ", e);
            errors.add("updUser", new ActionError("errors.GroupConflict"));
        }
        catch (Exception e)
        {
            log.error("updUser error: ", e);
            errors.add("updUser", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);

            return mapping.findForward("faile");
        }

        return (mapping.findForward("success"));
    }

    public final ActionForward getGroup(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        String id = request.getParameter("group");
        Group group = null;

        try
        {
            group = getService().getGroupById(id);
        }
        catch (Exception e)
        {
            log.error("getGroup error: ", e);
            errors.add("getGroup", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);

            return mapping.findForward("faile");
        }

        request.setAttribute("group", group);

        return (mapping.findForward("editgroup"));
    }
    
    public final ActionForward getUser(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        String id = (String) request.getSession().getAttribute("account");
        
        Account account = this.getSecurityService().findAccountById(id);

        request.setAttribute("account", account);

        return (mapping.findForward("userinfo"));
    }
    
    public final ActionForward updSelfInf(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        
        String id = (String) request.getSession().getAttribute("account");
        String oldPass = request.getParameter("oldPass");
        String newPass = request.getParameter("reNewPass");
        
        Account account = this.getSecurityService().findAccountById(id);
        
        if (!MD5.toMD5(oldPass).equals(account.getPassword()))
        {
            errors.add("updSelfInf", new ActionError("errors.PasswordIncorrect"));
            saveErrors(request, errors);
            return mapping.findForward("faile");
        }
        account.setPassword(MD5.toMD5(newPass));
        try
        {
            getService().updAccount(account);
        }
        catch (Exception e)
        {
            log.error("updSelfInf error: ", e);
            errors.add("updSelfInf", new ActionError("errors.UnKnowError"));
        }
        if (!errors.isEmpty())
        {
            saveErrors(request, errors);

            return mapping.findForward("faile");
        }
        return (mapping.findForward("success"));
    }
}
